package com.suncaper.tddmall.service;

import com.suncaper.tddmall.common.model.*;
import com.suncaper.tddmall.mapper.CartMapper;
import com.suncaper.tddmall.mapper.GoodsMapper;
import com.suncaper.tddmall.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    CartMapper cartMapper;

    public void addWishlist(Cart cart) {

        cartMapper.insert(cart);
    }

    public Cart selectByPrimaryKey(CartKey key) {
        Cart cart = cartMapper.selectByPrimaryKey(key);
        return cart;
    }

    public void increase(Cart cart) {
        cart.setGoodsNum(cart.getGoodsNum() + 1);
        cart.setTtMoney(cart.getTtMoney().add(goodsMapper.selectByPrimaryKey(cart.getGoodsId()).getPrice()));
        cartMapper.updateByPrimaryKeySelective(cart);
    }

    public void decrease(Cart cart) {
        if (cart.getGoodsNum() > 1) {
            cart.setGoodsNum(cart.getGoodsNum() - 1);
            cart.setTtMoney(cart.getTtMoney().subtract(goodsMapper.selectByPrimaryKey(cart.getGoodsId()).getPrice()));
        }
        cartMapper.updateByPrimaryKeySelective(cart);

    }


    public void deleteWishlist(CartKey key) {
        cartMapper.deleteByPrimaryKey(key);
    }

    public List<Cart> selectAll(String userId) {
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        return carts;
    }

    public void deleteAll(String userId) {
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId);
        cartMapper.deleteByExample(cartExample);
    }

    public void deleteSelect(String[] goodsId, String userId) {
        CartExample cartExample = new CartExample();
        int i;
        for (i = 0; i < goodsId.length; i++) {
            System.out.println(goodsId[i]);
            CartKey cartKey = new CartKey(userId,goodsId[i]);
            cartMapper.deleteByPrimaryKey(cartKey);
        }
    }
}
